package com.zjpavt.client.extenddevice;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.zjpavt.client.Connection;
import com.zjpavt.client.command.CommandPusher;
import com.zjpavt.client.enums.ExtendDeviceEnum;
import com.zjpavt.client.hal.ExtendDeviceManager;
import com.zjpavt.client.nativemethod.JnIMethod;
import com.zjpavt.client.util.Consts;
import com.zjpavt.client.util.PropertiesUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 电压电流告警
 * @author kangqi
 *
 */
@Slf4j
public class CheckAsAlarmDevice extends AbstractExtendDevice implements IExtendDevice {
    public static final ScheduledThreadPoolExecutor SCHEDULED_THREAD_POOL_EXECUTOR = new ScheduledThreadPoolExecutor(1);
    public CheckAsAlarmDevice(int extendNum) {
        super(extendNum,ExtendDeviceEnum.WITHOUT_DEVICE);
        // reFindCheckAsAlarmDevice();
    }


    /**
       * 检测电流电压告警
       */
    private synchronized void  reFindCheckAsAlarmDevice() {
        SCHEDULED_THREAD_POOL_EXECUTOR.schedule(()-> {
            log.debug("-------------------------------------------------------------------------------------------------------");
            //检测电流电压告警
            checkAsAlarmDevice() ;
        },3600, TimeUnit.SECONDS);
    }

    /**
     * 设备告警
     */
    private void checkAsAlarmDevice() {
        AbstractExtendDevice acDetector = ExtendDeviceManager.getInstance().findExtendDevice(getExtendNum(),true);
        AcDetector extendDevice= (AcDetector)acDetector;
        if(extendDevice != null && extendDevice.getDeviceType().getDeviceName().equals("ELECT")) {
            try {
                Map<String, String> voltageMap = new HashMap<String,String>();
                List<String[]>  voltageList = new ArrayList<String[]>();
                Map<String,String> voltageMessageMap = new HashMap<String,String>();
                List<String[]> voltageMessageList =  new ArrayList<String[]>();
                String elec_channel_is_testing = PropertiesUtil.getPropertiesDefault(Consts.KEY_ELEC_CHANNEL_IS_TESTING);
                String ecitStr[] = elec_channel_is_testing.split("");
                //是否发告警指令为1发送  为0 不发送
                if(null != elec_channel_is_testing && elec_channel_is_testing.contains("1")) {
                    //检测是否有异常
                    String phaseEveryLoop = extendDevice.getPhaseEveryLoop().toString();
                    phaseEveryLoop= phaseEveryLoop.substring(1, phaseEveryLoop.length()-1).replace(", ", "_");
                    String checkDeviceInfo = JnIMethod.sendMessage2ExtendDeviceByRs485(115200, getExtendNum(), "<AT_CHECK0_ELECT_"+extendDevice.getLoopNum()+"_"+phaseEveryLoop+">", 500);

                    String info = checkDeviceInfo.substring(7,checkDeviceInfo.length()-1);
                    info = info.substring(1,info.length()-1);
                    String infoStr[] = info.split("]\\[");
                    StringBuffer  voltageN = new StringBuffer();
                    voltageN.append("<N_");
                    for(String value :infoStr) {
                        String[] infos = value.split("_");
                        Integer keyInt = Integer.valueOf(infos[0]);
                        String str = keyInt+"_"+infos[1];
                        voltageN.append("[").append(str).append("]");
                    }
                    voltageN.append(">");
                    for(int i = 0; i <infoStr.length; i++) {
                        String []_info = infoStr[i].split("_");
                        String []listInfo =  {_info[0], _info[1].substring(6, _info[1].length())};

                        voltageList.add(listInfo);
                        voltageMap.put(_info[0], _info[1].substring(6, _info[1].length()));
                    }

                    for(String[]vol :voltageList) {
                        log.debug(vol[0]+vol[1]);
                        if(ecitStr[Integer.valueOf(vol[0])-1].equals("1") &&voltageMap.get(vol[0]).equals("00.0") ) {

                            String []listInfo =  {Integer.valueOf(vol[0]).toString(), "1"};
                            voltageMessageList.add(listInfo);
                            voltageMessageMap.put(Integer.valueOf(vol[0]).toString(), "1");


                        } else {
                            voltageMessageMap.put(Integer.valueOf(vol[0]).toString(), "0");
                            String []listInfo =  {Integer.valueOf(vol[0]).toString(), "0"};
                            voltageMessageList.add(listInfo);
                        }
                    }
                    StringBuffer  voltageR = new StringBuffer();
                    voltageR.append("<R_");
                    for(String[]vol :voltageMessageList) {
                        voltageR.append(vol[1]);
                    }
                    voltageR.append("_ALARM>");
                    //发送告警指令
                    CommandPusher.AlarmPush(Connection.getInstance(), voltageR.toString());
                    //String checkAsAlarmInfo = JnIMethod.sendMessage2ExtendDeviceByRs485(115200, getExtendNum(), voltageR.toString(), 500);
                    //log.debug(checkAsAlarmInfo);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
}
